package com.xayy.ds.service.impl;

import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.BeanUtil;
import cn.kawins.base.utils.CollUtil;
import cn.kawins.base.utils.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xayy.ds.model.DsNodeTreeInfo;
import com.xayy.ds.service.DsNodeTreeInfoService;
import com.xayy.mgt.model.EquipTreeInfo;
import com.xayy.mgt.model.NodeTreeInfo;
import com.xayy.mgt.model.vo.NodeTreeInfoVo;
import com.xayy.mgt.service.NodeInfoService;
import com.xtck.ha.common.core.domain.R;
import com.xtck.ha.common.core.web.service.dsimpl.BaseServiceImpl;
import com.xtck.ha.common.core.config.DsServerConfig;
import com.xtck.ha.common.core.utils.DomainUtils;
import com.xayy.ds.model.DsEquipTreeInfo;
import com.xayy.ds.service.DsEquipTreeInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: DsEquipTreeInfoService实现类
 * @Auther:liuyuan
 * @Date:2025-07-03
 */
@Slf4j
@Service
public class DsEquipTreeInfoServiceImpl extends BaseServiceImpl<DsEquipTreeInfo> implements DsEquipTreeInfoService {
  /**
  *
  * 冗余代码，为自定义开发DS-Server接口服务
  *
  */
   private static String TABLE_NAME = "EQUIP_TREE_INFO";
   private String getUrl(){
      return getDsServerConfig().getUrl();
   }

    @Autowired
    private DsNodeTreeInfoService nodeTreeInfoService;

    @Override
    public CheckResult<Object> getEquipTree() {
        List<DsEquipTreeInfo> equipTreeInfos = selectTList(new DsEquipTreeInfo());
        if (CollUtil.isEmpty(equipTreeInfos)) {
            return CheckResult.fail("卫星列表信息为空");
        }
        List<NodeTreeInfoVo> treeInfoVos =
                equipTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        List<NodeTreeInfoVo> tree = TreeUtil.toTree(0L, treeInfoVos);
        return CheckResult.success(tree);
    }


    @Override
    public CheckResult<Object> getEquipNodeTreeForNumber(Integer number) {
        List<DsEquipTreeInfo> equipTreeInfos = selectTList(new DsEquipTreeInfo());
        List<NodeTreeInfoVo> treeInfoVos = equipTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        List<NodeTreeInfoVo> tree = TreeUtil.toTree(0L, treeInfoVos);
        for(int i = 0 ; i < number ; i++){
            removeChild(tree);
            setEmptyChildIsNull(tree);
        }
        return CheckResult.success(tree);
    }

    /**
     * 设置空子节点为null
     */
    private void setEmptyChildIsNull(List<NodeTreeInfoVo> tree) {
        if(tree != null){
            for (NodeTreeInfoVo nodeTreeInfoVo : tree) {
                if(nodeTreeInfoVo.getChildList()!= null && nodeTreeInfoVo.getChildList().isEmpty()){
                    nodeTreeInfoVo.setChildList(null);
                }else{
                    setEmptyChildIsNull(nodeTreeInfoVo.getChildList());
                }
            }
        }
    }
    /**
     * 移除最后一级节点
     */
    private void removeChild(List<NodeTreeInfoVo> tree) {
        if(tree != null){
            for (NodeTreeInfoVo nodeTreeInfoVo : tree) {
                if(nodeTreeInfoVo.getChildList()!= null){
                    List<NodeTreeInfoVo> remove = new ArrayList<>();
                    for(NodeTreeInfoVo child:nodeTreeInfoVo.getChildList() ){
                        if(child.getChildList() != null){
                            removeChild(nodeTreeInfoVo.getChildList());
                        }else{
                            remove.add(child);
                        }
                    }
                    /*置为空，如果置为null则上级会被下次循环移除*/
                    nodeTreeInfoVo.getChildList().removeAll(remove);
                }
            }
        }
    }

    @Override
    public CheckResult<Object> addOrUpdate(DsEquipTreeInfo equipTreeInfo) {
        if (equipTreeInfo.getId() == null) {
            insertT(equipTreeInfo);
        } else {
            CheckResult<String> checkName = checkName(true, equipTreeInfo);
            if (checkName.no()) {
                return CheckResult.fail(checkName.getCheckMsg());
            }
            updateT(equipTreeInfo);
        }
        return CheckResult.success();
    }

    @Override
    public CheckResult<Object> deleteTreeById(Long id) {
        /*查询节点是否存在子节点，存在则不允许删除*/
        long count = count(DsEquipTreeInfo.builder().parentId(id).build());
        if (count > 0) {
            return CheckResult.fail("该节点存在子节点，不允许删除，如需删除请先删除子节点。");
        }
        int result = deleteTById(id);
        if (result > 0) {
            return CheckResult.success("删除成功");
        }
        return CheckResult.fail("删除失败");
    }

    @Override
    public CheckResult<Object> getTreeById(Long id) {
        DsEquipTreeInfo equipTreeInfo = selectTById(id);
        return CheckResult.success(equipTreeInfo);
    }

    @Override
    public CheckResult<Object> getEquipNodeTree() {
        List<DsEquipTreeInfo> equipTreeInfos = selectTList(new DsEquipTreeInfo());
        if (CollUtil.isEmpty(equipTreeInfos)) {
            return CheckResult.fail("卫星列表信息为空");
        }
        List<NodeTreeInfoVo> treeInfoVos =
                equipTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        // 查询卫星节点
        List<DsNodeTreeInfo> nodeTreeInfos = nodeTreeInfoService.selectTList(DsNodeTreeInfo.builder().level(0).build());
        List<NodeTreeInfoVo> treeInfoVos1 = nodeTreeInfos.stream().map(x -> BeanUtil.copyBean(x, NodeTreeInfoVo.class)).collect(Collectors.toList());
        treeInfoVos.addAll(treeInfoVos1);
        List<NodeTreeInfoVo> tree = TreeUtil.toTree(0L, treeInfoVos);
        return CheckResult.success(tree);
    }




    /**
     * 名称重复校验
     *
     * @param isUpdate
     *            是否更新
     * @param equipTreeInfo
     *            入参
     * @return 结果日志
     */
    private CheckResult<String> checkName(Boolean isUpdate, DsEquipTreeInfo equipTreeInfo) {

        DsEquipTreeInfo selectBody = DsEquipTreeInfo.builder()
                .nodeName(equipTreeInfo.getNodeName())
                .parentId(equipTreeInfo.getParentId())
                .build();
        if (Boolean.TRUE.equals(isUpdate)) {
            selectBody.setId(equipTreeInfo.getId());
        }
        List<DsEquipTreeInfo> equipTreeInfos = selectTList(selectBody);
        if (CollUtil.isNotEmpty(equipTreeInfos)) {
            return CheckResult.fail("节点名称：" + equipTreeInfo.getNodeName() + ",已存在");
        }
        return CheckResult.success();
    }

    /**
     * 新增节点设置节点层级卫星节点为0
     *
     * @param equipTreeInfo
     *            入参
     * @return 层级
     */
    private Integer setLevel(DsEquipTreeInfo equipTreeInfo) {
        DsEquipTreeInfo parent = selectTById(equipTreeInfo.getParentId());
        if (BeanUtil.isNotEmpty(parent)) {
            return parent.getLevel() + 1;
        }
        return 0;
    }
}
